#include "Shader.h"

CShader::CShader(void)
{
	m_pPixelShader = NULL;
	m_pVertexShader = NULL;
	m_pConstantTable = NULL;
}

CShader::~CShader(void)
{
	if(m_pPixelShader != NULL)
	{
		m_pPixelShader->Release();
		m_pPixelShader = NULL;
	}

	if(m_pVertexShader != NULL)
	{
		m_pVertexShader->Release();
		m_pVertexShader = NULL;
	}
}

void CShader::Init(IDirect3DDevice9* dev, const char* szFileName, int nType)
{
	m_pDevice = dev;
	m_nType = nType;
	if(m_pDevice == NULL)return;

	//	Assemble and set the pixel and or vertex shader
	HRESULT hRes;
	LPD3DXBUFFER Code = NULL;
	LPD3DXBUFFER ErrorMsgs = NULL;

	if(m_nType == PIXEL_SHADER)
		hRes = D3DXCompileShaderFromFile(szFileName, NULL, NULL, "Main", "ps_2_0", D3DXSHADER_DEBUG, &Code, &ErrorMsgs, &m_pConstantTable);
	else hRes = D3DXCompileShaderFromFile(szFileName, NULL, NULL, "Main", "vs_2_0", D3DXSHADER_DEBUG, &Code, &ErrorMsgs, &m_pConstantTable);

	if((FAILED(hRes)) && (ErrorMsgs != NULL))		//If failed
		return;

	if(m_nType == PIXEL_SHADER)
		hRes = m_pDevice->CreatePixelShader((DWORD*)Code->GetBufferPointer(), &m_pPixelShader);
	else hRes = m_pDevice->CreateVertexShader((DWORD*)Code->GetBufferPointer(), &m_pVertexShader);

	if(FAILED(hRes))
		exit(0);

}

void CShader::Begin()
{
	if(m_nType == PIXEL_SHADER)
		HRESULT hRes = m_pDevice->SetPixelShader(m_pPixelShader);
	else HRESULT hRes = m_pDevice->SetVertexShader(m_pVertexShader);
}

void CShader::End()
{
	if(m_nType == PIXEL_SHADER)
		HRESULT hRes = m_pDevice->SetPixelShader(NULL);
	else HRESULT hRes = m_pDevice->SetVertexShader(NULL);
}

D3DXHANDLE CShader::GetConstant(char* szName)
{
	return m_pConstantTable->GetConstantByName(NULL, szName);
}

void CShader::SetFloat(D3DXHANDLE h, float f)
{
	m_pConstantTable->SetFloat(m_pDevice, h, f);
}

void CShader::SetVector3(D3DXHANDLE h, D3DXVECTOR3 v)
{
	m_pConstantTable->SetValue(m_pDevice, h, &v, sizeof(D3DXVECTOR3));
}

void CShader::SetVector4(D3DXHANDLE h, D3DXVECTOR4 v)
{
	m_pConstantTable->SetVector(m_pDevice, h, &v);
}

void CShader::SetMatrix(D3DXHANDLE h, D3DXMATRIX m)
{
	m_pConstantTable->SetMatrix(m_pDevice, h, &m);
}